using System;
using System.IO;
using ClientTools.Library.DataTypes.Umbraco;
using umbraco.cms.businesslogic.media;

namespace ClientTools.Library.Manager
{
    public static class MediaManager
    {
        public static NodeCollection GetRootMedias(bool recursive)
        {
            return Media.GetRootMedias().ToNodeCollection(recursive);
        }

        //public NodeCollection GetMediaNode(int mediaId, bool recursive)
        //{
        //    return new umbraco.cms.businesslogic.media.Media(mediaId).Children.ToNodeCollection(recursive);
        //}

        public static NodeCollection GetMediasFromNode(int mediaId, bool recursive)
        {
            var umbracoMedia = new Media(mediaId);
            return GetMediasFromNode(umbracoMedia, recursive);
        }

        private static NodeCollection GetMediasFromNode(Media umbracoMedia, bool recursive)
        {
            return umbracoMedia.Children.ToNodeCollection(recursive);
        }

// ReSharper disable SuggestBaseTypeForParameter
        private static umbraco.cms.businesslogic.property.Property GetFilePropertyFromMedia(Media media)
// ReSharper restore SuggestBaseTypeForParameter
        {
            foreach (var umbracoProperty in media.GenericProperties)
                if (umbracoProperty.PropertyType.DataTypeDefinition.UniqueId == new Guid("5032a6e6-69e3-491d-bb28-cd31cd11086c"))
                    return umbracoProperty;
            return null;
        }

        public static bool DeleteMedia(int mediaId)
        {
            var media = new Media(mediaId);
            var fileProperty = GetFilePropertyFromMedia(media);
            if (fileProperty != null)
                DeleteMediaFiles(fileProperty.Id);
            media.delete();
            umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, 0, "ClientTools4Umbraco: Deleted media '" + mediaId + "'");
            return true;
        }

        private static void DeleteMediaFiles(int propertyId)
        {
            var mediaPath = Path.Combine(umbraco.GlobalSettings.FullpathToRoot, "media/" + propertyId);
            if (Directory.Exists(mediaPath))
            {
                foreach (var file in Directory.GetFiles(mediaPath))
                {
                    File.Delete(file);
                    umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, 0, "ClientTools4Umbraco: Deleted file '" + Path.GetFileName(file) + "' for media '" + propertyId + "'");
                }
                Directory.Delete(mediaPath);
            }
            return;
        }

        public static Node CreateNewImage(umbraco.BusinessLogic.User user, int parentMediaId, string imageName, byte[] content)
        {
            //var parentMedia = new umbraco.cms.businesslogic.media.Media(parentMediaId);

            var imageMediaType = MediaType.GetByAlias("Image");
            var newImage = Media.MakeNew(imageName, imageMediaType, user, parentMediaId);

            var propertyUmbracoFile = newImage.getProperty("umbracoFile");
            var mediaPath = Path.Combine(umbraco.GlobalSettings.FullpathToRoot, Path.Combine("media", propertyUmbracoFile.Id.ToString()));
            var fullFilePath = Path.Combine(mediaPath, imageName);

            if (!Directory.Exists(mediaPath))
                Directory.CreateDirectory(mediaPath);

            File.WriteAllBytes(fullFilePath, content);
            propertyUmbracoFile.Value = "/media/" + propertyUmbracoFile.Id + "/" + imageName;

            var ext = Path.GetExtension(imageName).Substring(1);
            newImage.getProperty("umbracoExtension").Value = ext;

            var fi = new FileInfo(fullFilePath);
            newImage.getProperty("umbracoBytes").Value = fi.Length.ToString();

            if (",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + ext.ToLower() + ",") > 0)
            {
                int fileWidth;
                int fileHeight;

                var fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);

                using (System.Drawing.Image image = System.Drawing.Image.FromStream(fs))
                {
                    fileWidth = image.Width;
                    fileHeight = image.Height;
                }
                fs.Close();
                //try
                //{
                newImage.getProperty("umbracoWidth").Value = fileWidth.ToString();
                newImage.getProperty("umbracoHeight").Value = fileHeight.ToString();
                //}
                //catch
                //{
                //    //umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, u, m.Id, "Zeile 116");
                //}

                // Generate thumbnail
// ReSharper disable PossibleLossOfFraction
                float fx = fileWidth / 100;
                float fy = fileHeight / 100; // subsampling factors
// ReSharper restore PossibleLossOfFraction
                // must fit in thumbnail size
                float f = Math.Max(fx, fy); if (f < 1) f = 1;
                var widthTh = (int)(fileWidth / f); 
                var heightTh = (int)(fileHeight / f);
                var fileNameThumb = fullFilePath.Replace("." + ext, "_thumb." + ext);
                using (var image = System.Drawing.Image.FromFile(fullFilePath))
                {

                    using (var bitmap = new System.Drawing.Bitmap(image, widthTh, heightTh))
                    {
                        //umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, user, parentMediaID, DateTime.Now.ToLongTimeString() + " - Jetzt wird das Thumbnail 4 erstellt...");
                        //umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, user, parentMediaID, DateTime.Now.ToLongTimeString() + " - fullFilePath: " + fullFilePath);
                        //umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, user, parentMediaID, DateTime.Now.ToLongTimeString() + " - fileNameThumb: " + fileNameThumb);
                        //try
                        //{
                        bitmap.Save(fileNameThumb, System.Drawing.Imaging.ImageFormat.Jpeg);
                        //}
                        //catch //(Exception ex)
                        //{
                        //    //umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, user, parentMediaID, DateTime.Now.ToLongTimeString() + " - Jetzt wird das Thumbnail 5 erstellt - " + fileNameThumb+ " - ");
                        //}
                    }
                }
            }
            return newImage.ToNode(false);
        }

        public static Node CreateNewFile(umbraco.BusinessLogic.User user, int parentMediaId, string fileName, byte[] content)
        {
            var imageMediaType = MediaType.GetByAlias("File");
            var newFile = Media.MakeNew(fileName, imageMediaType, user, parentMediaId);

            var propertyUmbracoFile = newFile.getProperty("umbracoFile");
            var mediaPath = Path.Combine(umbraco.GlobalSettings.FullpathToRoot, Path.Combine("media", propertyUmbracoFile.Id.ToString()));
            var fullFilePath = Path.Combine(mediaPath, fileName);

            if (!Directory.Exists(mediaPath))
                Directory.CreateDirectory(mediaPath);

            File.WriteAllBytes(fullFilePath, content);
            propertyUmbracoFile.Value = "/media/" + propertyUmbracoFile.Id + "/" + fileName;

            var ext = Path.GetExtension(fileName).Substring(1);
            newFile.getProperty("umbracoExtension").Value = ext;

            var fi = new FileInfo(fullFilePath);
            newFile.getProperty("umbracoBytes").Value = fi.Length.ToString();

            return newFile.ToNode(false);
        }

        public static Node CreateNewFolder(umbraco.BusinessLogic.User user, int parentMediaId, string folderName)
        {
            var mediaType = MediaType.GetByAlias("Folder");

            var newFolderMedia = Media.MakeNew(folderName, mediaType, user, parentMediaId);
            return newFolderMedia.ToNode(false);
        }
    }
}